// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.MPruchinvoice;
import com.javaweb.admin.entity.MPruchinvoiceDto;
import com.javaweb.admin.entity.MPruchinvoiceline;
import com.javaweb.admin.mapper.MPruchinvoiceMapper;
import com.javaweb.admin.mapper.MPruchinvoicelineMapper;
import com.javaweb.admin.query.MPruchinvoiceQuery;
import com.javaweb.admin.service.IMPruchinvoiceService;
import com.javaweb.admin.vo.mpruchinvoice.MPruchinvoiceInfoVo;
import com.javaweb.admin.vo.mpruchinvoice.MPruchinvoiceListVo;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.utils.ShiroUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
  * <p>
  * 采购发票主表 服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2024-01-17
  */
@Service
public class MPruchinvoiceServiceImpl extends BaseServiceImpl<MPruchinvoiceMapper, MPruchinvoice> implements IMPruchinvoiceService {

    @Autowired
    private MPruchinvoiceMapper mPruchinvoiceMapper;

    @Autowired
    private MPruchinvoicelineMapper mPruchinvoicelineMapper;
    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        MPruchinvoiceQuery mPruchinvoiceQuery = (MPruchinvoiceQuery) query;
        // 查询条件
        QueryWrapper<MPruchinvoice> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");
        if(!StringUtils.isEmpty(mPruchinvoiceQuery.getFph()))
        {
            queryWrapper.like("fph",mPruchinvoiceQuery.getFph());
        }
        if(!StringUtils.isEmpty(mPruchinvoiceQuery.getFpkjfmc()))
        {
            queryWrapper.like("fpkjfmc",mPruchinvoiceQuery.getFpkjfmc());
        }
        if(!StringUtils.isEmpty(mPruchinvoiceQuery.getRiqiBegin()))
        {
            queryWrapper.ge("fprq",mPruchinvoiceQuery.getRiqiBegin());
        }
        if(!StringUtils.isEmpty(mPruchinvoiceQuery.getRiqiEnd()))
        {
            queryWrapper.le("fprq",mPruchinvoiceQuery.getRiqiEnd());
        }
        queryWrapper.orderByDesc("fprq");

        // 获取数据列表
        IPage<MPruchinvoice> page = new Page<>(mPruchinvoiceQuery.getPage(), mPruchinvoiceQuery.getLimit());
        IPage<MPruchinvoice> pageData = mPruchinvoiceMapper.selectPage(page, queryWrapper);
//        pageData.convert(x -> {
//            MPruchinvoiceListVo mPruchinvoiceListVo = Convert.convert(MPruchinvoiceListVo.class, x);
//            return mPruchinvoiceListVo;
//        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        MPruchinvoice entity = (MPruchinvoice) super.getInfo(id);
        // 返回视图Vo
        MPruchinvoiceInfoVo mPruchinvoiceInfoVo = new MPruchinvoiceInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, mPruchinvoiceInfoVo);
        return mPruchinvoiceInfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(MPruchinvoice entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setUpdateTime(DateUtils.now());
            entity.setUpdateUser(ShiroUtils.getUserId());
        } else {
            entity.setCreateTime(DateUtils.now());
            entity.setCreateUser(ShiroUtils.getUserId());
        }
        return super.edit(entity);
    }

    @Override
    public JsonResult create(MPruchinvoiceDto dto) {
        try {
            MPruchinvoice entity = dto.getPruchinvoice();
            MPruchinvoiceline[] invoiceLines = dto.getPruchinvoiceLines();
//            String replaceno = "RP"+ DatePattern.PURE_DATETIME_FORMAT.format(DateUtils.now());
//            QueryWrapper<YYq005> queryWrapper = new QueryWrapper<YYq005>().eq("replaceno",replaceno);
//            queryWrapper.select("yybm,psdbm,ddlx,splx,ddbh,dcpsbs");
//            YYq005 yq005 = yYq005Mapper.selectOne(queryWrapper);
//
//            if(!StringUtils.isNull(yq005) && yq005.getStatus()!=0)
//            {
//                return JsonResult.error("该订单状态非【未提交】，不能再次保存。");
//            }
            entity.setStatus("0");
            mPruchinvoiceMapper.insert(entity);
            Integer index = 0;
            for (MPruchinvoiceline detail : invoiceLines) {
                detail.setPruchinvoiceid(entity.getId());
                mPruchinvoicelineMapper.insert(detail);
            }
            return JsonResult.success();
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }

    }


    @Override
    public JsonResult update(MPruchinvoiceDto dto) {
        try {
            MPruchinvoice entity = dto.getPruchinvoice();
            MPruchinvoiceline[] invoiceLines = dto.getPruchinvoiceLines();
//            String replaceno = "RP"+ DatePattern.PURE_DATETIME_FORMAT.format(DateUtils.now());
//            QueryWrapper<YYq005> queryWrapper = new QueryWrapper<YYq005>().eq("replaceno",replaceno);
//            queryWrapper.select("yybm,psdbm,ddlx,splx,ddbh,dcpsbs");
//            YYq005 yq005 = yYq005Mapper.selectOne(queryWrapper);
//
            if(!"0".equals(entity.getStatus()))
            {
                return JsonResult.error("该进项发票状态非【未传报】，不能再次保存。");
            }

            this.edit(entity);
            Integer index = 0;
            //
            Map<String,Object> param = new HashMap<>();
            param.put("pruchinvoiceid",entity.getId());
            mPruchinvoicelineMapper.deleteByMap(param);
            for (MPruchinvoiceline detail : invoiceLines) {
                detail.setPruchinvoiceid(entity.getId());
                mPruchinvoicelineMapper.insert(detail);
            }
            return JsonResult.success();
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }

    }


    @Override
    public JsonResult getPruchinvoiceList(BaseQuery query) {
        MPruchinvoiceQuery pruchinvoiceQuery = (MPruchinvoiceQuery)query;
        List<MPruchinvoiceListVo> list = mPruchinvoiceMapper.getPruchinvoiceList(pruchinvoiceQuery.getZxspbm(),pruchinvoiceQuery.getScph());
        return JsonResult.success(list);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(MPruchinvoice entity) {
        entity.setUpdateTime(DateUtils.now());
        entity.setUpdateUser(1);
        entity.setMark(0);
        return super.delete(entity);
    }

    @Override
    @Transactional
    public JsonResult deleteByIds(Integer[] ids) {
        Map<String,Object> param = new HashMap<>();
        for (int i = 0; i < ids.length; i++) {
            param.put("pruchinvoiceid",ids[i]);
            mPruchinvoicelineMapper.deleteByMap(param);
            mPruchinvoiceMapper.deleteById(ids[i]);
        }
        return JsonResult.success();
    }
}